<?php
abstract class ManageController extends Yaf_Controller_Abstract{
    protected $_layout;
    protected $redis;
    protected $now_url = '';

    public function init(){
        #设置
        $this->redis = new Config_RedisModel();
        $this->_layout = Yaf_Registry::get('layout');
        $controllerName = strtolower($this->getRequest()->getControllerName());  //控制器的名称
        $module = strtolower($this->getRequest()->module);
        $controller = strtolower($this->getRequest()->controller);
        $action = strtolower($this->getRequest()->action);
        $this->now_url = '/'.$module.'/'.$controller.'/'.$action.'/'; // 此时的路径

        $this->_view->current_controller = $this->_layout->current_controller = $controller;
        $this->_view->current_action = $this->_layout->current_action = $action;
        $this->_view->current_module = $this->_layout->current_module = $module;

        /*******用户是否登录**********/
        $user = $this->get_logined_user();  //用户信息
        if(empty($user)){  //没有登陆
            if($controllerName !== 'index' ){
                $this->set_popup_message('请先登陆');

                if(isset($_SERVER['REQUEST_URI'])){
                    $url = '/manage/index/login/?redirect_url='.urlencode($_SERVER['REQUEST_URI']);
                }else{
                    $url = '/manage/index/login/';
                }
                $this->redirect($url);
                return FALSE;
            }
            $this->_view->user_is_logined = $this->_layout->user_is_logined = 0; //没有登陆
        }else{
            #用户登陆后的操作
            $this->_view->user = $this->_layout->user = $user;
            $this->_view->user_is_logined = $this->_layout->user_is_logined = 1;  //是否登陆
        }


        #弹出的消息
        $this->_layout->popup_message = $this->get_popup_message();

        if($controllerName != 'index' ){
            if(empty($user) || $user['groupid'] < 1 ){
                $this->set_popup_message('没有权限No permission');
                $this->redirect('/manage/index/index/');
                exit;
            }
            $admin_roles_model = new AdminRolesModel();
            $check_auth = $admin_roles_model->checkPermiss($user['uid'], $module, $controller, $action);
            if(!$check_auth) {
                $this->set_popup_message('没有权限~No permission');
                $this->redirect('/manage/index/index/');
                exit;
            }
        }

        $admin_menu_model = new AdminMenuModel;
        $this->_view->admin_menus = $admin_menu_model->getMenu($controller);  //设置头部菜单信息
        $this->_layout->menu_list = $admin_menu_model->menu;
    }


    #获取分页参数
    public function getPagination($totalnum = 0, $page = 1, $page_size = 20){
        $page_num = ceil($totalnum / $page_size);
        $pagination = array(
            "record_count" => $totalnum,
            "page_count" => $page_num,
            "first" => 1,
            "last" => $page_num,
            "next" => $page_num > $page + 1 ? $page + 1 : $page_num,
            "prev" => $page - 1 > 1 ? $page - 1 : 1,
            "current" => $page,
            "page_size" => $page_size,
            "page_base" => 1,
        );
        return $pagination;
    }

    #当前登陆用户信息
    function get_logined_user()
    {
        $key = isset($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : '';
        if (!empty($key)) {
            $user = $this->redis->getData($key) ? $this->redis->getData($key) : array();
            return $user;
        } else {
            return array();
        }
    }

    #设置信息
    function set_popup_message($message){
        Yaf_Session::getInstance()->set('popup_message',$message);
    }

    #提取信息
    function get_popup_message(){
        #根据yaf自带的函数获取弹出的消息
        $message = Yaf_Session::getInstance()->get('popup_message');
        if(empty($message)){
            return '';
        }else{
            #删除消息缓存
            Yaf_Session::getInstance()->del('popup_message');
            return $message;
        }
    }

    #设置登陆用户的信息
    function set_current_user($user_info = array()){
        $expiretime = time() + 3600 * 24;
        $key = $_COOKIE['PHPSESSID'];
        $this->redis->setData($key, $user_info, $expiretime);
    }

    #写入日志
    function _log_result($str, $file_name = 'log.txt') {
        //目录
        $dir = "/data/bak/log/";
        #打开文件
        $fp = fopen($dir . $file_name,"a");
        #锁定，不允许其他人修改
        flock($fp, LOCK_EX) ;
        #写入
        fwrite($fp,"执行日期：".strftime("%Y%m%d%H%M%S",time()).": \n".$str."\n");
        #解锁
        flock($fp, LOCK_UN);
        #完毕
        fclose($fp);
    }

    #获取当前访问IP
    function getIp(){
        if (getenv('HTTP_CLIENT_IP')) {
            $now_ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_FORWARDED_FOR')) {
            $now_ip = getenv('HTTP_FORWARDED_FOR');
        } elseif (getenv('HTTP_X_FORWARDED')) {
            $now_ip = getenv('HTTP_X_FORWARDED');
        } elseif (getenv('HTTP_FORWARDED')) {
            $now_ip = getenv('HTTP_FORWARDED');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $now_ip = getenv('HTTP_X_FORWARDED_FOR');
        } else {
            $now_ip = $_SERVER['REMOTE_ADDR'];
        }
        return $now_ip;
    }


    #弹出错误信息，并且跳转
    function setError($msg, $url){
        $this->set_popup_message($msg);
        $this->redirect($url);
        exit;
    }

    function referer(){
        if (!empty($_SERVER['HTTP_REFERER'])){
            return $_SERVER['HTTP_REFERER'];
        }

        if (function_exists('apache_request_headers')) {
            $headers = apache_request_headers();
            if (!empty($headers['REFERER'])) {
                return $headers['REFERER'];
            }
        }

        return false;
    }
}
